package lac.serviceuint.handler;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import lac.serviceuint.cfg.Method;
import lac.serviceuint.cfg.MethodParam;
import lac.serviceuint.tool.StringToTypeInstantiation;

public class MethodHandler {
	
	private Method method ;
	
	private List<LogicHandler> logicHandlers = new ArrayList<LogicHandler>();
	
	private List<MethodParam> methodParams = new ArrayList<MethodParam>();

	public List<LogicHandler> getLogicHandlers() {
		return logicHandlers;
	}

	public void setLogicHandlers(List<LogicHandler> logicHandlers) {
		this.logicHandlers = logicHandlers;
	}

	public List<MethodParam> getMethodParams() {
		return methodParams;
	}

	public void setMethodParams(List<MethodParam> methodParams) {
		this.methodParams = methodParams;
	}
	
	public Method getMethod() {
		return method;
	}

	public void setMethod(Method method) {
		this.method = method;
	}

	public Map<String, Object> createParamMap(Object... params) throws Exception{
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		for(MethodParam methodParam : methodParams){
			String defalutValue = methodParam.getDefalutValue();
			String paramType = methodParam.getJavaClassType();
			Integer index = methodParam.getIndex();
			Object value = null;
			if(index<params.length){
				value = params[index];
			}
			if(defalutValue!=null && (index>params.length-1 || params[index]==null || !methodParam.getRestDefalutValue())){
				value = StringToTypeInstantiation.instance(paramType, defalutValue);
			}else if(defalutValue==null && value instanceof Map && !StringToTypeInstantiation.isBasicType(paramType)){
				value= StringToTypeInstantiation.transformTypeObject(paramType, value);
			}
			/*if((index>params.length-1 || params[index]==null) && defalutValue!=null){
				value = StringToTypeInstantiation.instance(paramType, defalutValue);
			}else{
				if(index<params.length){
					if(defalutValue!=null && !methodParam.getRestDefalutValue()){
						value = StringToTypeInstantiation.instance(paramType, defalutValue);
					}else{
						value = params[index];
						if(!StringToTypeInstantiation.isBasicType(paramType)){
							value= StringToTypeInstantiation.transformTypeObject(paramType, value);
						}
					}
					
				}
			}*/
			map.put(methodParam.getName(), value); 
		}
		return map;
	}
}
